package com.yifei.service.auth;

import com.yifei.model.dto.auth.UserAuthInfo;
import com.yifei.model.entity.auth.SysUserDetails;
import com.yifei.model.enums.ResultCode;
import com.yifei.service.system.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

@Service("sysUserDetailsService")
public class SysUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名获取认证信息
        UserAuthInfo userAuthInfo = sysUserService.getUserAuthInfo(username);
        // 如果未查找返回将异常抛出
        if (ObjectUtils.isEmpty(userAuthInfo)) {
            throw new UsernameNotFoundException(username);
        }
        // 用户无角色信息不能登录
        if (CollectionUtils.isEmpty(userAuthInfo.getRoles())) {
            throw new UsernameNotFoundException(ResultCode.USER_NOT_ROLE.getCode());
        }
        return new SysUserDetails(userAuthInfo);
    }
}